package enumandlambda;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author shkstart
 * @create 2022-12-11-22:24
 */
public class CyclicBarrierDemo1 {
    public static void main(String[] args) {
        //循环屏障
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("计数器为0 了");
            }
        });
        //线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            service.submit(()->{
                Thread currThread =Thread.currentThread();
                System.out.println("执行线程：" + currThread.getName());
                try {
                    Thread.sleep(500* finalI);

                //执行阻塞等待，让计数器-1，直到计数器为0后，一起执行阻塞的任务
                    cyclicBarrier.await();
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("线程执行完成"+ currThread.getName());
            });


        }
    }
}
